package map_tool

import (
	"encoding/json"
	"goscanner/logger"
	"goscanner/utils/err_util"
)

func GetString(dic map[string]any, key string) string {
	if v, ok := dic[key]; ok {
		switch v.(type) {
		case string:
			return v.(string)
		default:
			logger.Info(err_util.SprintTrace("目标类型与期望类型不一致, dict: ", ToJsonString(dic), ", key: ", key))
		}
	} else {
		logger.Info(err_util.SprintTrace("key不存在, dict: ", ToJsonString(dic), ", key: ", key))
	}
	return ""
}

func GetList(dic map[string]any, key string) []any {
	if v, ok := dic[key]; ok {
		switch v.(type) {
		case []any:
			return v.([]any)
		default:
			logger.Info(err_util.SprintTrace("目标类型与期望类型不一致, dict: ", ToJsonString(dic), ", key: ", key))
		}
	} else {
		logger.Info(err_util.SprintTrace("key不存在, dict: ", ToJsonString(dic), ", key: ", key))
	}
	return []any{}
}

func GetStringList(dic map[string]any, key string) []string {
	if v, ok := dic[key]; ok {
		switch v.(type) {
		case []string:
			return v.([]string)
		default:
			logger.Info(err_util.SprintTrace("目标类型与期望类型不一致, dict: ", ToJsonString(dic), ", key: ", key))
		}
	} else {
		logger.Info(err_util.SprintTrace("key不存在, dict: ", ToJsonString(dic), ", key: ", key))
	}
	return []string{}
}

func GetFloat64(dic map[string]any, key string) float64 {
	if v, ok := dic[key]; ok {
		switch v.(type) {
		case float64:
			return v.(float64)
		default:
			logger.Info(err_util.SprintTrace("目标类型与期望类型不一致, dict: ", ToJsonString(dic), ", key: ", key))
		}
	} else {
		logger.Info(err_util.SprintTrace("key不存在, dict: ", ToJsonString(dic), ", key: ", key))
	}
	return 0
}

func ToEntity(m any, target any) error {
	data, err := json.Marshal(m)
	if err != nil {
		return err
	}
	err = json.Unmarshal(data, target)
	if err != nil {
		return err
	}
	return nil
}

func ToJsonString(src map[string]any) string {
	data, _ := json.Marshal(src)
	return string(data)
}
